/*!
 * artDialog-plus v6.0.0
 * Date: 2013-12-25
 * https://github.com/aui/artDialog
 * (c) 2009-2013 TangBin, http://www.planeArt.cn
 *
 * This is licensed under the GNU LGPL, version 2.1 or later.
 * For details, see: http://www.gnu.org/licenses/lgpl-2.1.html
 */
define(function (require) {

	require('../css/ui-dialog.css');


	var Popup = (function () {


		var _count = 0;
		var _isIE6 = !('minWidth' in jQuery('html')[0].style);
		var _isFixed = !_isIE6;

		function Popup() {

			this.destroyed = false;

			this.__popup = jQuery('<div />')
				.attr({
					tabindex: '-1'
				})
				.css({
					display: 'none',
					position: 'absolute',
					left: 0,
					top: 0,
					bottom: 'auto',
					right: 'auto',
					margin: 0,
					padding: 0,
					outline: 0,
					border: '0 none',
					background: 'transparent'
				})
				.html(this.innerHTML)
				.appendTo('body');


			this.__backdrop = jQuery('<div />');


			// 使用 HTMLElement 作为外部接口使用，而不是 jquery 对象
			// 统一的接口利于未来 Popup 移植到其他 DOM 库中
			this.node = this.__popup[0];
			this.backdrop = this.__backdrop[0];

			_count++;
		}


		jQuery.extend(Popup.prototype, {
			/**
			 * 初始化完毕事件，在 show()、showModal() 执行
			 * @name Popup.prototype.onshow
			 * @event
			 */

			/**
			 * 关闭事件，在 close() 执行
			 * @name Popup.prototype.onclose
			 * @event
			 */

			/**
			 * 销毁前事件，在 remove() 前执行
			 * @name Popup.prototype.onbeforeremove
			 * @event
			 */

			/**
			 * 销毁事件，在 remove() 执行
			 * @name Popup.prototype.onremove
			 * @event
			 */

			/**
			 * 重置事件，在 reset() 执行
			 * @name Popup.prototype.onreset
			 * @event
			 */

			/**
			 * 焦点事件，在 foucs() 执行
			 * @name Popup.prototype.onfocus
			 * @event
			 */

			/**
			 * 失焦事件，在 blur() 执行
			 * @name Popup.prototype.onblur
			 * @event
			 */

			/** 浮层 DOM 素节点 */
			node: null,
			/** 遮罩 DOM 节点 */
			backdrop: null,
			/** 是否开启固定定位 */
			fixed: false,
			/** 判断对话框是否删除 */
			destroyed: true,
			/** 判断对话框是否显示 */
			open: false,
			/** close 返回值 */
			returnValue: '',
			/** 是否自动聚焦 */
			autofocus: true,
			/** 对齐方式 */
			align: 'bottom left',
			/** 设置遮罩背景颜色 */
			backdropBackground: '#000',
			/** 设置遮罩透明度 */
			backdropOpacity: 0.7,
			/** 内部的 HTML 字符串 */
			innerHTML: '',
			/** 类名 */
			className: 'fb-ui-popup',
			/**
			 * 显示浮层
			 * @param   {HTMLElement, Event}  指定位置（可选）
			 */
			show: function (anchor, position) {

				if (this.destroyed) {
					return this;
				}

				var that = this;
				var popup = this.__popup;

				this.__activeElement = this.__getActive();

				this.open = true;
				this.follow = anchor || this.follow;


				if (!this.__ready) {

					popup.addClass(this.className);

					if (this.modal) {
						this.__lock();
					}


					if (!popup.html()) {
						popup.html(this.innerHTML);
					}


					if (!_isIE6) {
						jQuery(window).on('resize', this.__onresize = function () {
							that.reset();
						});
					}


					this.__ready = true;
				}


				popup
					.addClass(this.className + '-show')
					.attr('role', this.modal ? 'alertdialog' : 'dialog')
					.css('position', this.fixed ? 'fixed' : 'absolute')
				;
				if (position) {
					popup.css(position);
				}

				popup.show(0);

				this.__backdrop.show(0);


				this.reset().focus();
				this.__dispatchEvent('show');

				return this;
			},

			shake: function () {
				var timerId = null;
				var style = this.__popup[0].style,
					p = [4, 8, 4, 0, -4, -8, -4, 0],
					fx = function () {
						style.marginLeft = p.shift() + 'px';
						if (p.length <= 0) {
							style.marginLeft = 0;
							clearInterval(timerId);
						}
					};
				p = p.concat(p.concat(p.concat(p)));
				timerId = setInterval(fx, 16);
				return this;
			},

			/** 显示模态浮层。参数参见 show() */
			showModal: function () {
				this.modal = true;
				return this.show.apply(this, arguments);
			},

			hide: function () {
				if (this.open) {
					this.__popup && this.__popup.hide && this.__popup.hide();
					this.__backdrop && this.__backdrop.hide();
					this.open = false;
					this.blur();
				}
				return this;
			},

			/** 关闭浮层 */
			close: function (result) {

				if (!this.destroyed && this.open) {

					if (result !== undefined) {
						this.returnValue = result;
					}

					this.__popup.hide().removeClass(this.className + '-show');
					this.__backdrop.hide();
					this.open = false;
					this.blur();
					this.__dispatchEvent('close');
				}

				return this;
			},

			/** fullscreen */
			fullscreen: function () {

				if (!this.destroyed && this.open) {

					if (result !== undefined) {
						this.returnValue = result;
					}

					this.__popup.hide().removeClass(this.className + '-show');
					this.__backdrop.hide();
					this.open = false;
					this.blur();
					this.__dispatchEvent('fullscreen');
				}

				return this;
			},

			/** resetwh */
			resetwh: function () {

				if (!this.destroyed && this.open) {

					if (result !== undefined) {
						this.returnValue = result;
					}

					this.__popup.hide().removeClass(this.className + '-show');
					this.__backdrop.hide();
					this.open = false;
					this.blur();
					this.__dispatchEvent('resetwh');
				}

				return this;
			},

			/** 销毁浮层 */
			remove: function () {

				if (this.destroyed) {
					return this;
				}

				this.__dispatchEvent('beforeremove');

				if (Popup.current === this) {
					Popup.current = null;
				}

				this.__unlock();
				this.__popup.remove();
				this.__backdrop.remove();


				// 恢复焦点，照顾键盘操作的用户
				this.blur();

				if (!_isIE6) {
					jQuery(window).off('resize', this.__onresize);
				}

				this.__dispatchEvent('remove');

				for (var i in this) {
					delete this[i];
				}

				return this;
			},
			/** 手动刷新位置 */
			reset: function () {

				if (this.fixed) {
					return this;
				}

				var elem = this.follow;

				if (elem) {
					this.__follow(elem);
				} else {
					this.__center();
				}

				this.__dispatchEvent('reset');

				return this;
			},
			/** 让浮层获取焦点 */
			focus: function () {

				var node = this.node;
				var current = Popup.current;

				if (current && current !== this) {
					current.blur(false);
				}

				// 检查焦点是否在浮层里面
				if (!jQuery.contains(node, this.__getActive())) {
					var autofocus = this.__popup.find('[autofocus]')[0];

					if (!this._autofocus && autofocus) {
						this._autofocus = true;
					} else {
						autofocus = node;
					}

					this.__focus(autofocus);
				}

				Popup.current = this;
				this.__popup.addClass(this.className + '-focus');
				this.__zIndex();
				this.__dispatchEvent('focus');

				return this;
			},
			/** 让浮层失去焦点。将焦点退还给之前的元素，照顾视力障碍用户 */
			blur: function () {

				var activeElement = this.__activeElement;
				var isBlur = arguments[0];


				if (isBlur !== false) {
					this.__focus(activeElement);
				}

				this._autofocus = false;
				this.__popup && this.__popup.removeClass(this.className + '-focus');
				this.__dispatchEvent('blur');

				return this;
			},
			/**
			 * 添加事件
			 * @param   {String}    事件类型
			 * @param   {Function}  监听函数
			 */
			addEventListener: function (type, callback) {
				this.__getEventListener(type).push(callback);
				return this;
			},
			/**
			 * 删除事件
			 * @param   {String}    事件类型
			 * @param   {Function}  监听函数
			 */
			removeEventListener: function (type, callback) {
				var listeners = this.__getEventListener(type);
				for (var i = 0; i < listeners.length; i++) {
					if (callback === listeners[i]) {
						listeners.splice(i--, 1);
					}
				}
				return this;
			},
			// 获取事件缓存
			__getEventListener: function (type) {
				var listener = this.__listener;
				if (!listener) {
					listener = this.__listener = {};
				}
				if (!listener[type]) {
					listener[type] = [];
				}
				return listener[type];
			},
			// 派发事件
			__dispatchEvent: function (type) {
				var listeners = this.__getEventListener(type);

				if (this['on' + type]) {
					this['on' + type]();
				}

				for (var i = 0; i < listeners.length; i++) {
					listeners[i].call(this);
				}
			},
			// 对元素安全聚焦
			__focus: function (elem) {
				// 防止 iframe 跨域无权限报错
				// 防止 IE 不可见元素报错
				try {
					// ie11 bug: iframe 页面点击会跳到顶部
					if (this.autofocus && !/^iframe$/i.test(elem.nodeName)) {
						elem.focus();
					}
				} catch (e) {
				}
			},
			// 获取当前焦点的元素
			__getActive: function () {
				try {// try: ie8~9, iframe #26
					var activeElement = document.activeElement;
					var contentDocument = activeElement.contentDocument;
					var elem = contentDocument && contentDocument.activeElement || activeElement;
					return elem;
				} catch (e) {
				}
			},
			// 置顶浮层
			__zIndex: function () {

				var index = Popup.zIndex++;

				// 设置叠加高度
				this.__popup.css('zIndex', index);
				this.__backdrop.css('zIndex', index - 1);
				this.zIndex = index;
			},
			// 居中浮层
			__center: function () {

				var popup = this.__popup;
				var $window = jQuery(window);
				var $document = jQuery(document);
				var fixed = this.fixed;
				var dl = fixed ? 0 : $document.scrollLeft();
				var dt = fixed ? 0 : $document.scrollTop();
				var ww = $window.width();
				var wh = $window.height();
				var ow = popup.width();
				var oh = popup.height();
				var left = (ww - ow) / 2 + dl;
				var top = (wh - oh) * 382 / 1000 + dt;// 黄金比例
				var style = popup[0].style;


				style.left = Math.max(parseInt(left), dl) + 'px';
				style.top = Math.max(parseInt(top), dt) + 'px';
			},
			// 指定位置 @param    {HTMLElement, Event}  anchor
			__follow: function (anchor) {

				var $elem = anchor.parentNode && jQuery(anchor);
				var popup = this.__popup;


				if (this.__followSkin) {
					popup.removeClass(this.__followSkin);
				}


				// 隐藏元素不可用
				if ($elem) {
					var o = $elem.offset();
					if (o.left * o.top < 0) {
						return this.__center();
					}
				}

				var that = this;
				var fixed = this.fixed;

				var $window = jQuery(window);
				var $document = jQuery(document);
				var winWidth = $window.width();
				var winHeight = $window.height();
				var docLeft = $document.scrollLeft();
				var docTop = $document.scrollTop();


				var popupWidth = popup.width();
				var popupHeight = popup.height();
				var width = $elem ? $elem.outerWidth() : 0;
				var height = $elem ? $elem.outerHeight() : 0;
				var offset = this.__offset(anchor);
				var x = offset.left;
				var y = offset.top;
				var left = fixed ? x - docLeft : x;
				var top = fixed ? y - docTop : y;


				var minLeft = fixed ? 0 : docLeft;
				var minTop = fixed ? 0 : docTop;
				var maxLeft = minLeft + winWidth - popupWidth;
				var maxTop = minTop + winHeight - popupHeight;


				var css = {};
				var align = this.align.split(' ');
				var className = this.className + '-';
				var reverse = {
					top: 'bottom',
					bottom: 'top',
					left: 'right',
					right: 'left'
				};
				var name = {
					top: 'top',
					bottom: 'top',
					left: 'left',
					right: 'left'
				};


				var temp = [{
					top: top - popupHeight,
					bottom: top + height,
					left: left - popupWidth,
					right: left + width
				}, {
					top: top,
					bottom: top - popupHeight + height,
					left: left,
					right: left - popupWidth + width
				}];


				var center = {
					left: left + width / 2 - popupWidth / 2,
					top: top + height / 2 - popupHeight / 2
				};


				var range = {
					left: [minLeft, maxLeft],
					top: [minTop, maxTop]
				};


				// 超出可视区域重新适应位置
				jQuery.each(align, function (i, val) {

					// 超出右或下边界：使用左或者上边对齐
					if (temp[i][val] > range[name[val]][1]) {
						val = align[i] = reverse[val];
					}

					// 超出左或右边界：使用右或者下边对齐
					if (temp[i][val] < range[name[val]][0]) {
						align[i] = reverse[val];
					}

				});


				// 一个参数的情况
				if (!align[1]) {
					name[align[1]] = name[align[0]] === 'left' ? 'top' : 'left';
					temp[1][align[1]] = center[name[align[1]]];
				}

				className += align.join('-');

				that.__followSkin = className;


				if ($elem) {
					popup.addClass(className);
				}


				css[name[align[0]]] = parseInt(temp[0][align[0]]);
				css[name[align[1]]] = parseInt(temp[1][align[1]]);
				popup.css(css);

			},
			// 获取元素相对于页面的位置（包括iframe内的元素）
			// 暂时不支持两层以上的 iframe 套嵌
			__offset: function (anchor) {

				var isNode = anchor.parentNode;
				var offset = isNode ? jQuery(anchor).offset() : {
					left: anchor.pageX,
					top: anchor.pageY
				};


				anchor = isNode ? anchor : anchor.target;
				var ownerDocument = anchor.ownerDocument;
				var defaultView = ownerDocument.defaultView || ownerDocument.parentWindow;

				if (defaultView == window) {// IE <= 8 只能使用两个等于号
					return offset;
				}

				// {Element Ifarme}
				var frameElement = defaultView.frameElement;
				var $ownerDocument = jQuery(ownerDocument);
				var docLeft = $ownerDocument.scrollLeft();
				var docTop = $ownerDocument.scrollTop();
				var frameOffset = jQuery(frameElement).offset();
				var frameLeft = frameOffset.left;
				var frameTop = frameOffset.top;

				return {
					left: offset.left + frameLeft - docLeft,
					top: offset.top + frameTop - docTop
				};
			},
			// 设置屏锁遮罩
			__lock: function () {

				var that = this;
				var popup = this.__popup;
				var backdrop = this.__backdrop;
				var backdropCss = {
					position: 'fixed',
					left: 0,
					top: 0,
					width: '100%',
					height: '100%',
					overflow: 'hidden',
					userSelect: 'none',
					opacity: 0,
					background: this.backdropBackground
				};


				popup.addClass(this.className + '-modal');


				// 避免遮罩不能盖住上一次的对话框
				// 如果当前对话框是上一个对话框创建，点击的那一瞬间它会增长 zIndex 值
				Popup.zIndex = Popup.zIndex + 2;
				this.__zIndex();


				if (!_isFixed) {
					jQuery.extend(backdropCss, {
						position: 'absolute',
						width: jQuery(window).width() + 'px',
						height: jQuery(document).height() + 'px'
					});
				}


				backdrop
					.css(backdropCss)
					.animate({
							opacity: this.backdropOpacity
						},
						150)
					.insertAfter(popup)
					// 锁住模态对话框的 tab 简单办法
					// 甚至可以避免焦点落入对话框外的 iframe 中
					.attr({
						tabindex: '0'
					})
					.on('focus', function () {
						that.focus();
					});

			},
			// 卸载屏锁遮罩
			__unlock: function () {

				if (this.modal) {
					this.__popup.removeClass(this.className + '-modal');
					this.__backdrop.remove();
					delete this.modal;
				}
			}

		});


		/** 当前叠加高度 */
		Popup.zIndex = 8024;


		/** 顶层浮层的实例 */
		Popup.current = null;


		return Popup;

	})();


	var dialog = (function () {


		//var Popup = Popup;//require('./popup');

		var defaults = {
			/* -----已注释的配置继承自 popup.js，仍可以再这里重新定义它----- */

			// 对齐方式
			//align: 'bottom left',

			// 是否固定定位
			//fixed: false,

			// 对话框叠加高度值(重要：此值不能超过浏览器最大限制)
			//zIndex: 1024,

			// 设置遮罩背景颜色
			backdropBackground: '#000',

			// 设置遮罩透明度
			backdropOpacity: 0.4,

			// 消息内容
			content: '<span class="fb-ui-dialog-loading">加载中..</span>',
			// 标题
			title: '',
			// 对话框状态栏区域 HTML 代码
			statusbar: '',
			// 自定义按钮
			button: null,
			// 确定按钮回调函数
			ok: null,
			// 取消按钮回调函数
			cancel: null,
			// 确定按钮文本
			okValue: '确定',
			// 取消按钮文本
			cancelValue: '取消',
			// 内容宽度
			width: "",
			// 内容高度
			height: "",
			// 内容与边界填充距离
			padding: '',
			// 对话框自定义 className
			skin: 'fb-ui-dialog',
			// 是否支持快捷关闭（点击遮罩层自动关闭）
			quickClose: true,
			// css 文件路径，留空则不会使用 js 自动加载样式
			// 注意：css 只允许加载一个
			cssUri: '../css/ui-dialog.css',
			// 模板（使用 table 解决 IE7 宽度自适应的 BUG）
			// js 使用 i="***" 属性识别结构，其余的均可自定义
			innerHTML: '<div i="dialog" class="fb-ui-dialog">'
				+ '<div class="fb-ui-dialog-arrow-a"></div>'
				+ '<div class="fb-ui-dialog-arrow-b"></div>'
				+ '<table class="fb-ui-dialog-grid">'
				+ '<tr>'
				+ '<td i="header" class="fb-ui-dialog-header">'
				+ '<button i="close" title="关闭" class="fb-ui-dialog-close">&#215;</button>'
				+ '<button i="fullscreen" title="全屏" class="fb-ui-dialog-close fb-ui-dialog-fullscreen">&#9633;</button>'
				+ '<div i="title" class="fb-ui-dialog-title"></div>'
				+ '</td>'
				+ '</tr>'
				+ '<tr>'
				+ '<td i="body" class="fb-ui-dialog-body">'
				+ '<div i="content" class="fb-ui-dialog-content"></div>'
				+ '</td>'
				+ '</tr>'
				+ '<tr>'
				+ '<td i="footer" class="fb-ui-dialog-footer">'
				+ '<div i="statusbar" class="fb-ui-dialog-statusbar"></div>'
				+ '<div i="button" class="fb-ui-dialog-button"></div>'
				+ '</td>'
				+ '</tr>'
				+ '</table>'
				+ '</div>'
		};//require('./dialog-config');
		var css = defaults.cssUri;

		// css loader: RequireJS & SeaJS
		//    if (css) {
		//        css = require[require.toUrl ? 'toUrl' : 'resolve'](css);
		//        css = '<link rel="stylesheet" href="' + css + '" />';
		//        if ($('base')[0]) {
		//            $('base').before(css);
		//        } else {
		//            $('head').append(css);
		//        }
		//    }

		var _version = '6.0.0';
		var _count = 0;
		var _expando = new Date() - 0;
		var _isIE6 = !('minWidth' in $('html')[0].style);
		var _isMobile = 'createTouch' in document && !('onmousemove' in document)
			|| /(iPhone|iPad|iPod)/i.test(navigator.userAgent);
		var _isFixed = !_isIE6 && !_isMobile;

		var artDialog = function (options, ok, cancel) {

			var originalOptions = options = options || {};

			if (typeof options === 'string' || options.nodeType === 1) {

				options = {
					content: options,
					fixed: !_isMobile
				};
			}

			options = $.extend(true, {}, artDialog.defaults, options);
			options._ = originalOptions;

			var id = options.id = options.id || _expando + _count;
			var api = artDialog.get(id);

			// 如果存在同名的对话框对象，则直接返回
			if (api) {
				return api.focus();
			}

			// 目前主流移动设备对fixed支持不好，禁用此特性
			if (!_isFixed) {
				options.fixed = false;
			}

			// 快捷关闭支持：点击对话框外快速关闭对话框
			if (options.quickClose) {
				options.modal = true;
				if (!originalOptions.backdropOpacity) {
					options.backdropOpacity = 0;
				}
			}

			// 按钮组
			if (!$.isArray(options.button)) {
				options.button = [];
			}


			// 确定按钮
			if (ok !== undefined) {
				options.ok = ok;
			}

			if (options.ok) {
				options.button.push({
					id: 'ok',
					value: options.okValue,
					callback: options.ok,
					title: "确定操作",
					autofocus: true
				});
			}

			// 取消按钮
			if (cancel !== undefined) {
				options.cancel = cancel;
			}

			if (options.cancel) {
				options.button.push({
					id: 'cancel',
					value: options.cancelValue,
					title: "取消操作",
					callback: options.cancel
				});
			}


			return artDialog.list[id] = new artDialog.create(options);
		};

		var popup = function () {
		};
		popup.prototype = Popup.prototype;
		var prototype = artDialog.prototype = new popup();

		artDialog.version = _version;

		artDialog.create = function (options) {
			var that = this;

			$.extend(this, new Popup());

			var $popup = $(this.node).html(options.innerHTML);

			this.options = options;
			this._popup = $popup;

			$.each(options, function (name, value) {
				if (typeof that[name] === 'function') {
					that[name](value);
				} else {
					that[name] = value;
				}
			});

			// 更新 zIndex 全局配置
			if (options.zIndex) {
				Popup.zIndex = options.zIndex;
			}

			// 设置 ARIA 信息
			$popup.attr({
				'aria-labelledby': this._$('title')
					.attr('id', 'title:' + this.id).attr('id'),
				'aria-describedby': this._$('content')
					.attr('id', 'content:' + this.id).attr('id')
			});

			// 关闭按钮
			this._$('close')
				.css('display', this.cancel === false ? 'none' : '')
				.attr('title', this.cancelValue)
				.on('click', function (event) {
					that._trigger('cancel');
					event.preventDefault();
				});

			// fullscreen
			this._$('fullscreen')
			//.css('display', this.cancel === false ? 'none' : '')
			//.attr('title', this.cancelValue)
				.on('click', function (event) {
					that.width(_top.$(_top).width() - 40);
					that.height(_top.$(_top).height() - that._$("header").height() - that._$("footer").height() - 70);
					//that._trigger('_fullscreen');
					event.preventDefault();
				});

			// 添加视觉参数
			this._$('dialog').addClass(this.skin);
			this._$('body').css('padding', this.padding);

			// 按钮组点击
			$popup.on('click', '[data-id]', function (event) {
				var $this = $(this);
				if (!$this.attr('disabled')) {// IE BUG
					that._trigger($this.data('id'));
				}

				event.preventDefault();
			});

			// 点击遮罩自动关闭对话框
			if (options.quickClose) {
				$(this.backdrop).on(
					'onmousedown' in document ? 'mousedown' : 'click',
					function () {
						that._trigger('cancel');
					});
			}

			// ESC 快捷键关闭对话框
			this._esc = function (event) {
				var target = event.target;
				var nodeName = target.nodeName;
				var rinput = /^input|textarea$/i;
				var isTop = Popup.current === that;
				var keyCode = event.keyCode;

				// 避免输入状态中 ESC 误操作关闭
				if (!isTop || rinput.test(nodeName) && target.type !== 'button') {
					return;
				}

				if (keyCode === 27) {
					that._trigger('cancel');
				}
			};

			$(document).on('keydown', this._esc);
			this.addEventListener('remove', function () {
				$(document).off('keydown', this._esc);
				delete artDialog.list[this.id];
			});

			_count++;

			artDialog.oncreate(this);

			return this;
		};

		artDialog.create.prototype = prototype;

		$.extend(prototype, {

			content: function (html) {

				this._$('content').empty('')
					[typeof html === 'object' ? 'append' : 'html'](html);

				return this.reset();
			},
			/**
			 * 设置标题
			 * @param    {String}   标题内容
			 */
			title: function (text) {
				this._$('title').html(text);
				this._$('header')[text ? 'show' : 'hide']();
				return this;
			},
			/** 设置宽度 */
			width: function (value) {
				this._$('content').css('width', value);
				this._width = value;
				return this.reset();
			},
			/** 设置高度 */
			height: function (value) {
				this._$('content').css('height', value);
				this._height = value;
				return this.reset();
			},
			/**
			 * 设置按钮组
			 * @param   {Array, String}
			 */
			button: function (args) {
				args = args || [];
				var that = this;
				var html = '';
				this.callbacks = {};

				this._$('footer')[args.length ? 'show' : 'hide']();

				if (typeof args === 'string') {
					html = args;
				} else {
					$.each(args, function (i, val) {

						val.id = val.id || val.value;
						that.callbacks[val.id] = val.callback;

						html +=
							'<button'
							+ ' type="button"'
							+ ' data-id="' + val.id + '"'
							+ ' title="' + (val.title || "") + '"'
							+ (val.disabled ? ' disabled' : '')
							+ (val.autofocus ? ' autofocus class="fb-ui-dialog-autofocus"' : '')
							+ '>'
							+ val.value
							+ '</button>';

					});
				}

				this._$('button').html(html);

				return this;
			},
			statusbar: function (html) {
				this._$('statusbar')
					.html(html)[html ? 'show' : 'hide']();

				return this;
			},
			_$: function (i) {
				return this._popup.find('[i=' + i + ']');
			},
			// 触发按钮回调函数
			_trigger: function (id) {

				var fn = this.callbacks[id];

				return typeof fn !== 'function' || fn.call(this) !== false ?
					this.close().remove() : this;
			},

			done: function () {
				var me = this;
				setTimeout(function () {
					me.close().remove();
				}, 1300);
			}

		});

		artDialog.oncreate = $.noop;

		/** 最顶层的对话框API */
		artDialog.getCurrent = function () {
			return Popup.current;
		};

		/**
		 * 根据 ID 获取某对话框 API
		 * @param    {String}    对话框 ID
		 * @return   {Object}    对话框 API (实例)
		 */
		artDialog.get = function (id) {
			return id === undefined
				? artDialog.list
				: artDialog.list[id];
		};

		artDialog.list = {};

		/**
		 * 默认配置
		 */
		artDialog.defaults = defaults;

		$.dialog = artDialog;

		return artDialog;
	})();//require('./dialog');


	var drag = (function () {

		var $window = $(window);
		var $document = $(document);
		var isTouch = 'createTouch' in document;
		var html = document.documentElement;
		var isIE6 = !('minWidth' in html.style);
		var isLosecapture = !isIE6 && 'onlosecapture' in html;
		var isSetCapture = 'setCapture' in html;


		var types = {
			start: isTouch ? 'touchstart' : 'mousedown',
			over: isTouch ? 'touchmove' : 'mousemove',
			end: isTouch ? 'touchend' : 'mouseup'
		};


		var getEvent = isTouch ? function (event) {
			if (!event.touches) {
				event = event.originalEvent.touches.item(0);
			}
			return event;
		} : function (event) {
			return event;
		};


		var DragEvent = function () {
			this.start = $.proxy(this.start, this);
			this.over = $.proxy(this.over, this);
			this.end = $.proxy(this.end, this);
			this.onstart = this.onover = this.onend = $.noop;
		};

		DragEvent.types = types;

		DragEvent.prototype = {
			start: function (event) {
				event = this.startFix(event);

				$document
					.on(types.over, this.over)
					.on(types.end, this.end);

				this.onstart(event);
				return false;
			},
			over: function (event) {
				event = this.overFix(event);
				this.onover(event);
				return false;
			},
			end: function (event) {
				event = this.endFix(event);

				$document
					.off(types.over, this.over)
					.off(types.end, this.end);

				this.onend(event);
				return false;
			},
			startFix: function (event) {
				event = getEvent(event);

				this.target = $(event.target);
				this.selectstart = function () {
					return false;
				};

				$document
					.on('selectstart', this.selectstart)
					.on('dblclick', this.end);

				if (isLosecapture) {
					this.target.on('losecapture', this.end);
				} else {
					$window.on('blur', this.end);
				}

				if (isSetCapture) {
					this.target[0].setCapture();
				}

				return event;
			},
			overFix: function (event) {
				event = getEvent(event);
				return event;
			},
			endFix: function (event) {
				event = getEvent(event);

				$document
					.off('selectstart', this.selectstart)
					.off('dblclick', this.end);

				if (isLosecapture) {
					this.target.off('losecapture', this.end);
				} else {
					$window.off('blur', this.end);
				}

				if (isSetCapture) {
					this.target[0].releaseCapture();
				}

				return event;
			}

		};


		/**
		 * 启动拖拽
		 * @param   {HTMLElement} elem  被拖拽的元素
		 * @param   {Event} event 触发拖拽的事件对象。可选，若无则监听 elem 的按下事件启动
		 */
		DragEvent.create = function (elem, event) {
			var $elem = $(elem);
			var dragEvent = new DragEvent();
			var startType = DragEvent.types.start;
			var noop = function () {
			};
			var className = elem.className
				.replace(/^\s|\s.*/g, '') + '-drag-start';

			var minX;
			var minY;
			var maxX;
			var maxY;

			var api = {
				onstart: noop,
				onover: noop,
				onend: noop,
				off: function () {
					$elem.off(startType, dragEvent.start);
				}
			};


			dragEvent.onstart = function (event) {
				var isFixed = $elem.css('position') === 'fixed';
				var dl = $document.scrollLeft();
				var dt = $document.scrollTop();
				var w = $elem.width();
				var h = $elem.height();

				minX = 0;
				minY = 0;
				maxX = isFixed ? $window.width() - w + minX : $document.width() - w;
				maxY = isFixed ? $window.height() - h + minY : $document.height() - h;

				var offset = $elem.offset();
				var left = this.startLeft = isFixed ? offset.left - dl : offset.left;
				var top = this.startTop = isFixed ? offset.top - dt : offset.top;

				this.clientX = event.clientX;
				this.clientY = event.clientY;

				$elem.addClass(className);
				api.onstart.call(elem, event, left, top);
			};


			dragEvent.onover = function (event) {
				var left = event.clientX - this.clientX + this.startLeft;
				var top = event.clientY - this.clientY + this.startTop;
				var style = $elem[0].style;

				left = Math.max(minX, Math.min(maxX, left));
				top = Math.max(minY, Math.min(maxY, top));

				style.left = left + 'px';
				style.top = top + 'px';

				api.onover.call(elem, event, left, top);
			};


			dragEvent.onend = function (event) {
				var position = $elem.position();
				var left = position.left;
				var top = position.top;
				$elem.removeClass(className);
				api.onend.call(elem, event, left, top);
			};


			dragEvent.off = function () {
				$elem.off(startType, dragEvent.start);
			};


			if (event) {
				dragEvent.start(event);
			} else {
				$elem.on(startType, dragEvent.start);
			}

			return api;
		};

		return DragEvent;
	})();//require('./drag');

	dialog.notice = function (content, options) {
		options = $.extend({}, {
				title: "提醒",
				content: "" +
					"	<table class='fb-ui-dialog-table fb-ui-dialog-alert-table'>" +
					"	<tr>" +
					"		<td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td>" +
					"		<td class='fb-ui-dialog-table-content'><br>" + content + "</td>" +
					"	</tr>" +
					"	</table>",
				padding: "10px",
				width: 400,
				lock: true,
				fixed: true,
				quickClose: false
			},
			options || {});

		var dia = _top.$.dialog(options);

		window.__popup = dia.__popup;
		var topHeight = _top.$(_top).height();
		var topWidth = _top.$(_top).width();

		dia.show(null, {
			left: topWidth - dia.__popup.width() - 10,
			top: topHeight
		});

		dia.__popup.animate({ top: topHeight - dia.__popup.height() - 10 }, 800);

		return dia;
	};


	/**
	 * 确认提示
	 * @param content
	 * @param ok
	 * @param cancel
	 * @param options
	 * @returns {*}
	 */
	dialog.confirm = function (content, ok, cancel, options) {
		options = $.extend({}, {
				title: "请确认以下操作",
				content: "<table class='fb-ui-dialog-table fb-ui-dialog-confirm-table'><tr><td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td><td class='fb-ui-dialog-table-content'><br>" + content + "</td></tr></table>",
				width: 400,
				lock: true,
				quickClose: false,
				padding: "10px",
				okValue: '确 定',
				cancelValue: "取 消",
				ok: ok || $.noop,
				cancel: cancel || $.noop
			},
			options || {});
		return _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);
	};

	/**
	 * tips
	 * @param content
	 * @param time
	 * @param options
	 * @returns {*}
	 */
	dialog.tips = function (content, time, options) {
		options = $.extend({}, {
				width: 300,
				padding: "10px",
				quickClose: false,
				content: content || "请稍等..."
			},
			options || {});
		var dia = _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);

		setTimeout(function () {
			dia.close().remove();
			dia = null;
		}, time || 2000);

		return dia;
	};

	/**
	 * 打开
	 * @param url
	 * @param options
	 * @returns {*}
	 */
	dialog.open = function (url, options) {
		options = $.extend({}, {
				title: "业务操作",
				url: url,
				lock: true,
				quickClose: false
			},
			options || {});
		return _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);
	};

	/**
	 * 提醒
	 * @param content
	 * @param ok
	 * @param options
	 * @returns {*}
	 */
	dialog.alert = function (content, ok, options) {
		options = $.extend({}, {
				title: "提醒",
				content: "<table class='fb-ui-dialog-table fb-ui-dialog-alert-table'><tr><td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td><td class='fb-ui-dialog-table-content'><br>" + content + "</td></tr></table>",
				padding: "10px",
				width: 400,
				lock: true,
				quickClose: false,
				okValue: '确 定',
				ok: ok || $.noop
			},
			options || {});
		return _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);
	};

	/**
	 * 警告
	 * @param content
	 * @param ok
	 * @param cancel
	 * @param options
	 * @returns {*}
	 */
	dialog.warn = function (content, ok, cancel, options) {
		options = $.extend({}, {
				title: "警告",
				content: "<table class='fb-ui-dialog-table fb-ui-dialog-warn-table'><tr><td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td><td class='fb-ui-dialog-table-content'><br>" + content + "</td></tr></table>",
				width: 400,
				lock: true,
				quickClose: false,
				okValue: '确 定',
				ok: ok || $.noop
			},
			options || {});
		return _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);
	};

	/**
	 * 错误
	 * @param content
	 * @param ok
	 * @param options
	 * @returns {*}
	 */
	dialog.error = function (content, ok, options) {
		options = $.extend({}, {
				title: "错误",
				width: 400,
				lock: true,
				quickClose: false,
				content: "<table class='fb-ui-dialog-table fb-ui-dialog-error-table'><tr><td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td><td class='fb-ui-dialog-table-content'><br>" + content + "</td></tr></table>",
				padding: "10px",
				okValue: '确 定',
				ok: ok || $.noop
			},
			options || {})
		return _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);
	};

	dialog.success = function (content, ok, options) {
		options = $.extend({}, {
				title: "操作成功",
				content: "<table class='fb-ui-dialog-table fb-ui-dialog-success-table'><tr><td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td><td class='fb-ui-dialog-table-content'><br>" + content + "</td></tr></table>",
				padding: "10px",
				width: 400,
				lock: true,
				quickClose: false,
				okValue: '确 定',
				ok: ok || $.noop
			},
			options || {});
		return _top.$.dialog(options)[options && options.lock === true ? "showModal" : "show"]((options && options.follow) || null);
	};

	dialog.wait = function (content, time, options) {

		options = $.extend(true, {}, {
				width: 300,
				padding: "10px",
				quickClose: false,
				content: content || "请稍等..."
			},
			options || {});

		return this.tips.apply(this, [
			"<table class='fb-ui-dialog-table fb-ui-dialog-warn-table'><tr><td width='100' class='fb-ui-dialog-table-icon'>&nbsp;</td><td class='fb-ui-dialog-table-content'><br>" + content + "</td></tr></table>", time, options
		]);
	};


	/**
	 * 创建
	 * @param api
	 */
	dialog.oncreate = function (api) {

		var options = api.options;
		var originalOptions = options._;

		// 页面地址
		var url = options.url;
		// 页面加载完毕的事件
		var oniframeload = options.oniframeload;

		var $iframe;

		if (url) {
			this.padding = options.padding = 0;

			$iframe = $('<iframe name="' + api.id + '" />');

			$iframe.attr({
				src: url,
				width: '100%',
				height: '100%',
				allowtransparency: 'yes',
				frameborder: 'no'
				//                scrolling: 'no'
			}).on('load', function () {
				var test;

				try {
					// 跨域测试
					test = $iframe[0].contentWindow.frameElement;
				} catch (e) {
					firebird.error(url, "跨域测试失败");
				}

				//if (test) {
				//
				//	if (!options.width) {
				//		api.width($iframe.contents().width());
				//	}
				//
				//	if (!options.height) {
				//		api.height($iframe.contents().height());
				//	}
				//}

				if (oniframeload) {
					oniframeload.call(api);
				}

			});

			api.addEventListener('beforeremove', function () {

				// 重要！需要重置iframe地址，否则下次出现的对话框在IE6、7无法聚焦input
				// IE删除iframe后，iframe仍然会留在内存中出现上述问题，置换src是最容易解决的方法
				$iframe.attr('src', 'about:blank').remove();

			}, false);

			api.content($iframe[0]);

			api.iframeNode = $iframe[0];

		}

		// 对于子页面呼出的对话框特殊处理
		// 如果对话框配置来自 iframe
		if (!(originalOptions instanceof Object)) {

			var un = function () {
				api.close().remove();
			};

			// 找到那个 iframe
			for (var i = 0; i < frames.length; i++) {
				try {
					if (originalOptions instanceof frames[i].Object) {
						// 让 iframe 刷新前时候也关闭对话框，
						// 防止要执行的对象被强制收回导致 IE 报错：“不能执行已释放 Script 的代码”
						$(frames[i]).one('unload', un);
						break;
					}
				} catch (e) {
				}
			}
		}

		// 拖拽支持
		$(api.node).on(drag.types.start, '[i=title]', function (event) {
			// 排除气泡类型的对话框
			if (!api.follow) {
				api.focus();
				drag.create(api.node, event);
			}
		});

	};

	dialog.get = function (id) {

		// 从 iframe 传入 window 对象
		if (id && id.frameElement) {
			var iframe = id.frameElement;
			var list = dialog.list;
			var api;
			for (var i in list) {
				api = list[i];
				if (api.node.getElementsByTagName('iframe')[0] === iframe) {
					return api;
				}
			}
			// 直接传入 id 的情况
		} else if (id) {
			return dialog.list[id];
		}

	};

	return dialog;

});